<template>
  <!-- 插入子节点 -->
  <ul class="children" :class="'level-'+props.childrenLevel">
    <div
      class="children-mind-node"
      v-for="(item, index) in currentNode"
      :key="item.id"
    >
      <span
        :class="toggleIcon ? 'toggle toggle-close' : 'toggle toggle-expand'"
        @click="toggle_icon"
      >
      </span>
      <li v-if="toggleIcon" :class="isFirst(index) ? 'child-insert first-child' : 'child-insert'">
        <div class="node-content">
          <div
            class="title"
            v-show="!item.isEditing"
            @dblclick="startEditing(item)"
          >
            {{ item.label }}
            <el-icon>
              <Edit />
            </el-icon>
          </div>
          <div v-show="item.isEditing">
            <el-input
              :id="`inputRef${item.id}`"
              v-model="item.label"
              @keyup.enter="saveEditing(item)"
              @blur="saveEditing(item)"
            ></el-input>
          </div>
          <!-- 操作 -->
          <div class="opration">
            <div>
              <svg
                _ngcontent-nee-c286=""
                version="1.1"
                id="图层_1"
                xmlns="http://www.w3.org/2000/svg"
                xmlns:xlink="http://www.w3.org/1999/xlink"
                x="0px"
                y="0px"
                viewBox="0 0 16 16"
                xml:space="preserve"
                width="16px"
                height="16px"
              >
                <path
                  _ngcontent-nee-c286=""
                  d="M14.9,7.8l-2.5-3.1l2.5-3.7h-11V0.6C3.9,0.3,3.6,0,3.2,0C2.9,0,2.6,0.3,2.6,0.6v14.3H1.7
                                c-0.3,0-0.6,0.3-0.6,0.6c0,0.3,0.3,0.6,0.6,0.6h3c0.3,0,0.6-0.3,0.6-0.6c0-0.3-0.3-0.6-0.6-0.6H3.9V7.8H14.9z"
                  class="st0"
                  style="fill: #ffd700"
                ></path>
              </svg>
              <span class="TaskOperation" @click="openDrawer(item)">{{
                item.state
              }}</span>
            </div>
            <div class="btn-group">
              <el-button
                type="primary"
                @click="addChild(item)"
                :icon="Plus"
                title="添加子节点"
                circle
              />
              <el-button
                type="danger"
                @click="confirmDeleteChildNode(item)"
                :icon="Minus"
                title="删除子节点"
                circle
              />
              <el-button
                type="danger"
                @click="confirmDeleteCurrentNode(item)"
                :icon="Delete"
                title="删除当前节点"
                circle
              />
            </div>
          </div>
        </div>
        <!-- 插入子节点 -->
        <mind-node :childrenLevel="props.childrenLevel+1" :node="item.children" @delete-child="deleteCurrentNode">
        </mind-node>
      </li>
    </div>
  </ul>
  <!-- Drawer组件，确保它只被渲染一次 -->
  <DrawerTable
    v-if="drawerVisible"
    :nodeData="selectedNodeItem"
    @close="drawerVisible = false"
  />
</template>

<script setup>
import { ref, onMounted, computed, nextTick } from "vue";
import DrawerTable from "@/components/MindMap/DrawerTable.vue";
//引用图标
import { Edit, Plus, Minus, Delete } from "@element-plus/icons-vue";
import { ElMessageBox } from "element-plus";
import { List } from "echarts";
import { ElNotification } from "element-plus";

let props = defineProps({
  node: List,
  childrenLevel:Number,
});

//默认图标展开
let toggleIcon = ref(true);
const emit = defineEmits(["delete-child"]);
const currentNode = computed(() => props.node || []);
// 控制Drawer组件的显示
const drawerVisible = ref(false);
const selectedNodeItem = ref(null);

// 打开Drawer组件的方法
const openDrawer = (openNode) => {
  selectedNodeItem.value = openNode; //选中的节点对象赋值给变量
  drawerVisible.value = true; // 显示Drawer组件
};

// 添加一个方法来初始化节点的编辑状态
const initializeEditingState = (node) => {
  node.forEach((item) => {
    item.isEditing = false; // 初始化编辑状态
    if (item.children && item.children.length) {
      initializeEditingState(item.children); // 递归初始化子节点
    }
  });
};

onMounted(() => {
  initializeEditingState(currentNode.value); // 初始化编辑状态
  console.log("level:"+props.childrenLevel)
});

//添加子节点
const addChild = (parentNode) => {
  //新节点
  let newNode = {
    id: Date.now(),
    label: "新字节点标题",
    create_time: formatDate(Date.now()),
    state: "新建",
    children: [],
  };
  //给当前节点的children数组添加子节点
  parentNode.children.push(newNode);
  ElNotification({
    title: "成功",
    message: "新节点添加成功",
    type: "success",
  });
};

//删除子节点提示
const confirmDeleteChildNode = (nodeToDelete) => {
  ElMessageBox.confirm("您确定要删除该节点的所有子节点吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      // 用户确认删除
      deleteChildNode(nodeToDelete);
    })
    .catch((e) => {
      // 用户取消删除
      console.log("取消删除");
      console.log(e);
    });
};
//删除子节点
const deleteChildNode = (nodeToDelete) => {
  // 找到父节点并从其 children 数组中移除该节点
  nodeToDelete.children = [];
  ElNotification({
    title: "成功",
    message: "子节点删除成功",
    customClass: "el-notification",
    type: "success",
  });
};

const confirmDeleteCurrentNode = (nodeToDelete) => {
  ElMessageBox.confirm("您确定要删除该节点及其子节点吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      // 用户确认删除
      deleteCurrentNode(nodeToDelete);
    })
    .catch((e) => {
      // 用户取消删除
      console.log("取消删除");
      console.log(e);
    });
};

//删除当前节点
const deleteCurrentNode = (nodeToDelete) => {
  //删除当前节点全部交给父组件节点去统一删除
  emit("delete-child", nodeToDelete); // 触发自定义事件，并传递要删除的节点
};

//编辑标题
const startEditing = (item) => {
  item.isEditing = true;
  nextTick(() => {
    // 正确引用输入框
    const inputRefKey = `inputRef${item.id}`;
    const inputRef = ref(null);
    inputRef.value = document.getElementById(inputRefKey);
    if (inputRef.value) {
      inputRef.value.focus();
    }
  });
};

const saveEditing = (item) => {
  item.isEditing = false;
};

//判断是否第一个节点
const isFirst = (index) => {
  return index == 0;
};

// 时间格式化函数
const formatDate = (dateString) => {
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  const hours = date.getHours().toString().padStart(2, "0");
  const minutes = date.getMinutes().toString().padStart(2, "0");
  const seconds = date.getSeconds().toString().padStart(2, "0");

  // 返回格式化后的日期时间字符串
  return `${year}/${month}/${day} ${hours}:${minutes}:${seconds} GMT+08:00`;
};

//切换展开图标及功能
const toggle_icon = () => {
    if (toggleIcon.value) {
        toggleIcon.value = false
    } else {
        toggleIcon.value = true
    }
}
</script>

<style lang="scss" scoped>
//子节点
.children {
  position: relative;
  height: fit-content;

  .children-mind-node {
    //第一个元素
    &:first-child > li::before {
      content: "";
      display: block;
      position: absolute;
      height: calc(50% + 24px);
      border-left: 1px solid var(--mindmap-line-color);
      left: -15px;
      top: 50%;
    }

    //中间的元素
    &:not(:first-child):not(:last-child) > li::before {
      content: "";
      display: block;
      position: absolute;
      height: calc(100% + 24px);
      border-left: 1px solid var(--mindmap-line-color);
      left: -15px;
      top: 0%;
    }

    //最后一个元素
    &:last-child > li::before {
      content: "";
      display: block;
      position: absolute;
      height: 50%;
      border-left: 1px solid var(--mindmap-line-color);
      left: -15px;
      top: 0%;
    }

    //只有一个元素的时
    &:only-child > li::before {
      height: 0;
    }

    .child-insert {
      position: relative;
      display: flex;
      align-items: center;
      z-index: 1;
      min-height: 72px;
      margin-left: 36px;
      margin-top: 24px;

      .node-content {
        position: relative;
        padding: 12px 16px;
        background-color: var(--base-bg);
        box-shadow: var(--box-line-shadow);
        white-space: nowrap;
        height: 70px;
        min-width: 206px;
        max-width: 396px;
        border-radius: 8px;
        cursor: move;

        //内容标题
        .title {
          font-weight: 700;
          font-size: var(--base-font-size);
          cursor: pointer;
          display: flex;
          align-items: center;

          .el-icon {
            margin-left: 5px;
          }
        }

        //操作按钮
        .opration {
          display: flex;
          justify-content: space-between;
          align-items: center;
          color: yellow;
          padding: 5px 0;

          & > div {
            vertical-align: middle;
          }

          .TaskOperation {
            color: var(--base-text);
            cursor: pointer;
          }
        }
      }

      // 每个节点前面加横接线 该显示正常
      &::after {
        content: "";
        display: block;
        position: absolute;
        width: 15px; // 调整宽度以匹配你的设计需求
        height: 0px; // 厚度设为1px以匹配横接线的宽度
        border-top: 1px solid var(--mindmap-line-color);
        left: -15px; // 调整位置以连接到竖接线
        top: 50%;
      }
    }

    .first-child {
      margin-top: 0;
    }

    //展开缩小节点
    .toggle {
      position: absolute;
      top: 50%;
      left: 0;
      margin-top: -7px;
      height: 14px;
      width: 14px;
      cursor: pointer;
      z-index: 99;
      background: url("@/assets/img/common/combine-first.png") no-repeat;
    }

    //展开关闭按钮
    .toggle-close {
      background-position: 0 -282px;

      &:hover {
        background-position: 0 -268px;
      }
    }

    //展开打开按钮
    .toggle-expand {
      background-position: 0 -254px;

      &:hover {
        background-position: 0 -240px;
      }
    }
  }

  //给每个非空元素添加水平竖线
  &:not(:empty):after {
    content: "";
    position: absolute;
    top: 50%;
    left: 15px;
    height: 0;
    width: 6px;
    border-top: 1px solid var(--mindmap-line-color);
  }
}
</style>